import { useStore } from '@/hooks';
import { Button, Dialog, Form, ResponsiveGrid, Icon, Input, Switch, Message } from '@alifd/next';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, driverModel, column, ENUMS } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable, toJS } from 'mobx';
import AttachmentForm from './AttachmentForm';
import QR from '@/components/QR/QR';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

const DataForm = ({ modal, id, onCancel, onSubmit, addDriver }) => {
  const { driverStore: store } = useStore();
  const [QRModal, setQRModal] = useState({});
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'view');
  const formProps = isViewMode ? { field: false } : {};
  const [driver] = useState(() => observable({}));
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      await store.getCompany({ search: { status: 1 }, pg: { size: 999 } });
      if (id) {
        const res = await store.get({ search: { username: id }, pg: { page: 0, size: 10 } });
        const data = res[0];
        await store.getVehicle({ companyId: data?.driverInfo?.companyId });
        editCtx.origin = _.cloneDeep(data);
        _.assign(driver, data);
        _.set(driver, data.driverStatus, ENUMS.status[data?.driverStatus]);
        _.set(driver, data.dutyStatus, ENUMS.status[data.dutyStatus]);
        store.getCompany({ search: { status: 1 }, pg: { size: 999 } });
      } else {
        _.set(driver, 'driverInfo.driverStatus', 1);
        _.set(driver, 'driverInfo.dutyStatus', 0);
        _.set(driver, 'driverInfo.type', 1);
        _.set(driver, 'driverInfo.companyId', addDriver?.companyId || '');
      }
    })();
  }, []);

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(driver, name, value);
    if (name === 'driverInfo.dutyStatus') {
      if (!toJS(driver.driverInfo.dutyVehicleId)) {
        Message.warning({ content: t`请先选择值班车辆` });
        _.set(driver, 'driverInfo.dutyStatus', 0);
      }
      if (!value) {
        _.set(driver, 'driverInfo.dutyVehicleId', '');
      }
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  // 重载definitions中的定义，处理一些根据上下文的动态定义
  const overrideModel = {
    driverInfo: {
      independentAccount: {
        collectionAccountInformation: {
          name: {
            label: t`真实姓名`,
          },
          accountIdentification: {
            label: t`账号标识`,
            ui: {
              renderer: (v) => (<Input
                value={v}
                placeholder={t`请扫码绑定收款帐号`}
                addonAfter={!isViewMode && <Button type="primary" onClick={handleQrCode}>{t`扫码设置`}</Button>}
              />),
            },
          },
        },
      },
      dutyVehicleId: {
        label: t`值班车辆`,
        ui: {
          renderer: (v) => <TauSimpleSelect data={store.vehicle} value={v} />,
        },
      },
      dutyStatus: {
        label: t`值班状态`,
        ui: {
          renderer: (v) => (<Switch
            checkedChildren="出车"
            unCheckedChildren="收车"
            autoWidth
            checked={v}
            size="small"
            disabled={id}
          />),
        },
      },
    },
  };

  // 扫码
  const handleQrCode = async () => {
    try {
      const { username, fullname } = driver;
      const baseUrl = await store.addProfitShare(username);
      setQRModal({
        open: true,
        okText: '下载',
        onCancel: QROnCancel,
        name: fullname,
        baseUrl,
      });
    } catch (error) {
      console.log('🚀 _ file: DataForm.jsx:124 _ error:', error);
    }
  };

  // 关闭二维码
  const QROnCancel = () => {
    setQRModal({ open: false });
  };

  /**
   * @description 提交表单实现修改车辆
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: DataForm.jsx:139 _ errors:', errors);
      return;
    }
    const { driverStatus, dutyStatus } = driver?.driverInfo || {};
    if (_.isBoolean(driverStatus)) {
      driver.driverInfo.driverStatus = driverStatus ? 1 : 0;
    }
    if (_.isBoolean(dutyStatus)) {
      driver.driverInfo.dutyStatus = dutyStatus ? 1 : 0;
    }
    onSubmit?.(driver);
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={driver}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基础信息`} />
      <FieldsGrid
        formData={driver}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={[
          'driverInfo.companyId', 'fullname', 'driverInfo.dateBirth',
          'vehicle.permanentLandName', 'driverInfo.hkMobile', 'mobile',
          'driverInfo.number', 'driverInfo.address', 'driverInfo.dutyVehicleId',
          'driverInfo.dutyStatus', 'driverInfo.driverStatus', 'gender']}
      />
      <TitleGrid title={t`分账信息`} />
      <FieldsGrid
        formData={driver}
        overrideModel={overrideModel}
        mode={modal[0]}
        fields={['name', 'accountIdentification'].map((n) => `driverInfo.independentAccount.collectionAccountInformation.${n}`)}
      />
      <TitleGrid title={t`驾驶信息`} />
      <FieldsGrid
        formData={driver}
        mode={modal[0]}
        fields={[
          'licenseMainland.licenseNo',
          'licenseMainland.vechileType',
          'licenseMainland.validityDate',
          'internationalLicense',
          'licenseHK.licenseNo',
          'licenseHK.vechileType',
          'licenseHK.validityDate'].map((n) => `driverInfo.${n}`)}
      />
      <AttachmentPanel driver={driver?.driverInfo} modal={modal[0]} />
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <QR modal={QRModal} />
    </Form>
  );
};

const AttachmentPanel = observer(({ driver, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'view';

  useEffect(() => {
    if (driver?.attachments?.length) setIdx(0);
  }, [driver?.attachments]);

  const handleAddAttachment = () => {
    if (!driver?.attachments) driver.attachments = [];
    driver?.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(driver.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    driver.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid title={<span>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={7}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(driver?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, driverModel.driverInfo.attachments[0]),
              column('description', {}, driverModel.driverInfo.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`chanel:${driver.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(driver.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              driver.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              driver.attachments[idx]?.binaryId.splice(driver.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(driver.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(DataForm);
